// api
import Api from "@/api"
//  默认公共路由 menus
import router from "@/router"
import Util from "./util";
import Vue from "vue"

let MENUS = [];
const UserModule = {
  state: {
    user_info: null,  //  用户信息
    user_menus: null,  //  api获取用户权限菜单
    user_is_logined: false,  //  用户是否登陆
  },
  getters: {
    user_menus(state) {
      //  需要归并默认 menus
      const dafaultRoutes = router.options.routes.filter(menu => {
        return !menu.hideinmenu
      })
      MENUS = Util.transformData(null, state.user_menus);
      return dafaultRoutes.concat(MENUS);
    },
    user_is_logined(state) {
      return state.user_is_logined || Boolean(Cookies.get("token"))
    }
  },
  mutations: {
    SET_USER_LOGINED(state, payload) {
      state.user_is_logined = payload
    },
    SET_USER_INFO(state, payload) {
      state.user_info = payload
    },
    SET_USER_MENUS(state, payload) {
      state.user_menus = payload
    },
    //  添加权限路由
    ADD_ROUTERS() {
      setTimeout(() => {
        router.addRoutes(Util.addRoutesCycle(MENUS));
      }, 100)
    }
  },
  actions: {
    SET_USER_INFO(context) {
      return new Promise((resolve, reject) => {
      })
    },
    SET_USER_MENUS(context) {
      return new Promise((resolve, reject) => {
        Api.UserGetMenus().then(res => {
          if (res) {
            context.commit("SET_USER_MENUS", res.data);
            context.commit("ADD_ROUTERS");
            resolve(res)
          } else {
            context.commit("SET_USER_MENUS", []);
            context.commit("ADD_ROUTERS");
            reject(false)
          }
        })
      })
    }
  }
}
export default UserModule;
